package com.bp.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.bp.common.utils.uuid.UUID;
import com.bp.system.domain.ShortMsgParam;
import com.bp.system.service.IShortMsgService;
import com.bp.system.service.ShortMsgTemplateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @author shaominjie
 * @description TODO
 * @date 2020/12/7 0007 11:34
 */
@Service
public class ShortMsgServiceImpl implements IShortMsgService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShortMsgServiceImpl.class);
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    //三通短信发送
    private static final String SANTONG_URL="http://www.bpsms.cn/rest/mq/sms/producer/sendTemplateMessage";
    //三通短信发送
    private static final String SANTONG_APPKEY="66ECE75A36994EF4B26E2C7DFAC0233F";
    //三通短信发送
    private static final String SANTONG_SGIN ="湖州市民政局";
    @Override
    public void shortMsgSend(final ShortMsgParam shortMsgParam) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                sendMsgBySanTong(shortMsgParam);
            }
        });
    }

    private static void sendMsgBySanTong(ShortMsgParam shortMsgParam){

        long startTime=System.currentTimeMillis();
        if(LOGGER.isInfoEnabled()){
            LOGGER.info("大汉三通短信API短信发送调用开始");
        }
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String extendId= UUID.fastUUID().toString();
        try{
            ShortMsgTemplateEnum shortMsgTemplateEnum=shortMsgParam.getShortMsgTemplateEnum();
            String postData="accessKey="+SANTONG_APPKEY+
                    "&phones="+shortMsgParam.getReceiveSign()+
                    "&sign="+SANTONG_SGIN+
                    "&extendId="+extendId+
                    "&templateId="+shortMsgTemplateEnum.getMsgId()+
                    "&templateParam=["+ JSON.toJSONString(shortMsgParam.getMsgParam())+"]";

            URL url = new URL(SANTONG_URL);
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接主机服务器超时时间：5000毫秒
            connection.setConnectTimeout(5000);
            // 设置读取主机服务器返回数据超时时间：10000毫秒
            connection.setReadTimeout(10000);
            connection.addRequestProperty("encoding", "UTF-8");//添加请求属性
            connection.setDoInput(true);//允许输入
            connection.setDoOutput(true);//允许输出
            connection.setRequestMethod("POST");//POST请求要在获取输入输出流之前设置否则报错
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //connection.setRequestProperty("Content-Type", "application/json");
            //输出
            os = connection.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(postData);
            bw.flush();
            //输入
            is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is,"UTF-8");
            br = new BufferedReader(isr);
            String line;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine()) != null){
                sb.append(line);
            }
            Map<String,String> jsonResult=(Map<String, String>) JSON.parse(sb.toString());
            String resultCode=jsonResult.get("CODE");

            String templateContext=shortMsgTemplateEnum.getValue();
            Map<String,String> paramMap=shortMsgParam.getMsgParam();
            for(String key: paramMap.keySet()){
                String keyStr=String.valueOf(key);
                templateContext=templateContext.replace("${"+keyStr+"}", paramMap.get(keyStr));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            assert connection != null;
            connection.disconnect();// 关闭远程连接
        }

        long endTime=System.currentTimeMillis();
        if(LOGGER.isInfoEnabled()){
            LOGGER.info("大汉三通短信API短信发送调用结束，耗时："+(endTime-startTime)+"ms");
        }
    }

    public static void main(String[] args) {

        ShortMsgParam shortMsgParam = new ShortMsgParam();
        shortMsgParam.setReceiveSign("18868823007");
        shortMsgParam.setShortMsgTemplateEnum(ShortMsgTemplateEnum.RESERVATION_SUCCESS_MSG);
        sendMsgBySanTong(shortMsgParam);
    }
}
